package de.grosjohann.android.feuerwehr.service;

import java.util.List;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import de.grosjohann.android.feuerwehr.R;
import de.grosjohann.android.feuerwehr.domain.FireIndex;
import de.grosjohann.android.feuerwehr.domain.WeatherWarning;
import de.grosjohann.android.feuerwehr.notification.Notify;
import de.grosjohann.android.feuerwehr.util.FileUtil;
import de.grosjohann.android.feuerwehr.util.JSON2ObjectUtil;
import de.grosjohann.android.feuerwehr.webservice.WeatherWsFacade;

public class WeatherNotificationService
  extends IntentService {

  public static final String WEATHER_DATA = "feuerwehr.WeatherData";

  private static final String NAME = "WeatherNotificationService";

  public WeatherNotificationService() {
    super(NAME);
  }

  @Override
  protected void onHandleIntent(Intent newIntent) {

    Log.d(NAME, "handle");

    Context context = getApplicationContext();

    try {
      /*
       * neue Daten empfangen, alte Daten lesen.
       */
      String json = WeatherWsFacade.getWeather(context);
      String lastReceive = FileUtil.readFile(context, WEATHER_DATA);

      /*
       * Empfangene Daten speichern.
       */
      FileUtil.writeFile(context, WEATHER_DATA, json);

      /*
       * Vergleich des WaldbrandIndex.
       */
      FireIndex fi = JSON2ObjectUtil.getFireIndex(json);
      FireIndex lastFi = JSON2ObjectUtil.getFireIndex(lastReceive);

      if (!fi.equals(lastFi)) {
        String msg =
            getString(R.string.lblFireIndex) + ": " + getString(R.string.lblLevel) + " " + fi.getLevel().getLevel();
        Notify.getInstance().add(context, msg);
      }

      /*
       * Vergleich der Wetterwarnungen.
       */
      List<WeatherWarning> wws = JSON2ObjectUtil.getWeatherWarningList(json);
      List<WeatherWarning> oldWws = JSON2ObjectUtil.getWeatherWarningList(lastReceive);

      if (!wws.equals(oldWws)) {
        WeatherWarning highestWarning = WeatherWarning.getHighestWarning(wws);

        String msg =
            getString(R.string.lblWeatherWarning) + ": " + getString(R.string.lblLevel) + " "
                + highestWarning.getLevel().getLevel();

        Notify.getInstance().add(context, msg);
      }

    } catch (Exception ex) {
      Log.e(NAME, ex.getMessage(), ex);
    }
  }
}
